import cv2
import os

def video_to_frames(video_file, output_folder):
    # 创建输出文件夹
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)
    
    # 读取视频文件
    cap = cv2.VideoCapture(video_file)
    
    # 检查视频是否成功打开
    if not cap.isOpened():
        print("Error: Could not open video.")
        return
    
    frame_count = 0
    step = 5
    file_name = video_file.split('/')[-1].split('.')[0]
    # print(file_name)
    while True:
        # 逐帧读取视频
        ret, frame = cap.read()
        # 如果读取完毕，跳出循环
        if not ret:
            break
        if frame_count % step == 0:
            # 构建输出图片的文件名
            output_filename = os.path.join(output_folder, f"frame_{frame_count}.jpg")       
            # 保存图片
            cv2.imwrite(output_filename, frame)    
        frame_count += 1
    
    # 释放视频对象
    cap.release()
    print(f"Total frames extracted: {frame_count}")

# 使用示例
video_file = './parseVideo/嘻嘻.mp4'
output_folder = './output/'
video_to_frames(video_file, output_folder)
